package com.augurit.gzcgwsp.smartformCsdlwj.web;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.script.ScriptEngine;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.JbpmException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.printDoc.web.form.YwPrintDocForm;
import com.augurit.gzcgwsp.sendNotice.service.IYwMtbjlshInfoService;
import com.augurit.gzcgwsp.smartformCsdlwj.common.SmartDao;
import com.augurit.gzcgwsp.smartformCsdlwj.service.IYwGgcsServices;
import com.augurit.gzcgwsp.smartformCsdlwj.web.form.GgcsForm;
import com.augurit.gzcgwsp.wfex.app.doc.IOaDocCodeServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfBusTemplateServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfTemplateAttachmentRefServiceEX;
import com.augurit.gzcgwsp.wfex.bi.web.form.WfTemplateAttachmentRefFormEX;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.smartform.factory.ScriptEngineFactory;
import com.augurit.smartform.service.IFormExecuteService;
import com.augurit.smartform.service.IWfSupportService;
import com.augurit.smartform.test.TestService;
import com.augurit.wf.app.doccode.service.IOaDocCodeService;
import com.augurit.wf.bi.convert.WfBusInstanceConvertor;
import com.augurit.wf.bi.service.IWfBusInstanceService;
import com.augurit.wf.bi.web.form.WfActElemPrivDefForm;
import com.augurit.wf.bi.web.form.WfBusInstanceForm;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.entity.Jbpm4HistTask;
import com.augurit.wf.common.entity.WfBusInstance;
import com.augurit.wf.common.form.TraceRecord;
import com.augurit.wf.common.form.WfBusSaveResult;
import com.augurit.wf.common.service.IWfService;
import com.augurit.wf.common.tag.opinion.WfOpinionTag;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientExtAction;

@Results({
	@Result(name = CrudActionSupport.RELOAD, location = "ggcs.action", type = "redirect"),
	@Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP),
	@Result(name = WfConstant.PRINT_DIR, location = WfConstant.PRINT_DIR_JSP),
	@Result(name = WfConstant.MAKE_DOCUMENT, location = "/gzcgwsp/wfex/client/common/make-noline-document.jsp"),
	@Result(name = "yqData", location = "/gzcgwsp/gcxk/ggcs-yqb.jsp"),
	@Result(name = "toBjgzData", location = "/gzcgwsp/gcxk/ggcs-bjgz.jsp")
})
	
public class GgcsAction extends WfBusClientExtAction<GgcsForm>  {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Autowired
    private IWfServiceEX wfServiceEX;

	@Autowired
	private TestService testService;

	@Autowired
	private IWfSupportService wfSupportService;

	@Autowired
	private IFormExecuteService formExecuteService;
	
	@Autowired
	private IWfBusTemplateServiceEX wfBusTemplateServiceEX;

	@Autowired
	private IOaDocCodeService docCodeService;

	@Autowired
	private IOaDocCodeServiceEX oaDocCodeServiceEX;

	@Autowired
	private IWfBusInstanceService wfBusInstanceService;

	@Autowired
	private IWfTemplateAttachmentRefServiceEX wfTemplateAttachmentRefServiceEX;

	@Autowired
	private IYwGgcsServices ywGgcsServices;
	
	@Autowired
	private IYwPrintDocService ywPrintDocService;
	@Autowired
	private IWfService wfService;
	
	@Autowired
	private SmartDao smartDao;
	@Autowired
	private IYwMtbjlshInfoService ywMtbjlshInfoService;
	
	private Long id;

	private Page<Map> page = new Page<Map>(20);
	private Map pageMap = new HashMap();

	private GgcsForm form;
	/**
	 * 保存表单
	 */
	public String wfBusSave() throws IOException {
		this.executeWfSaveServer(); // 保存之前执行后端JS函数
		Long id = null;
		try {
			WfBusInstanceTaskForm task = wfSupportService.wfBusSave(getRequest());
			String entityKey = task.getMasterEntityKey();

			Map map = getRequest().getParameterMap();
			
			String ysl = BaseAction.getRequest().getParameter("SS_CCGBSQB_YSL");
			String sqdw = ((String[]) map.get("SS_CCGBSQB_SQDW"))[0]; // 单位
			String acceptNo = updateAcceptNoAndSumary(entityKey, sqdw,ysl); // 更新入受理号以及汇总字段

//			GgcsForm form = new GgcsForm();
			if (task != null && task.getMasterEntityKey() != null) {
				id = Long.valueOf(task.getMasterEntityKey());
			}
			form.setId(id);

			task.setMessage(acceptNo); // 设置受理编号
			
			if (ysl.equals("1")) { // 更新预受理状态
				ywGgcsServices.changeYslState(id, 2l,null);
			}			
			getRequest().setAttribute("CurrUserName",this.getLoginUser().getUser().getUserName());
			  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			if (form.getDfsj() == null) {//答复时间
				if(form.getSqrq()==null){//申请日期
	            	form.setSqrq(new Date());
	            	 String sqrqstr = dateFormat.format(new Date());
	            	 this.saveSqrq(entityKey,sqrqstr);//保存申请日期和呈批时间
	            }
	            String durationExpression = wfServiceEX.getProcDueExpressIonByTaskInstDbid(task.getTaskInstDbid());
	            Date dfsj = wfServiceEX.calculateDueDate(form.getSqrq(), durationExpression);
	           
	          
	            String dfsjStr = dateFormat.format(dfsj);
	            this.saveDfsj(entityKey,dfsjStr);
	            form.setDfsj(dfsjStr);
	        }
			WfUtils.renderWfBusSaveJson(task, form);

		} catch (Exception e) {
			Struts2Utils.renderJson("{success:false,text:保存失败！}");// 保存失败
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 更新受理号和更新汇总字段
	 * 
	 * @param entityId
	 * @param tbrq
	 * @param sqdw
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private String updateAcceptNoAndSumary(String entityId, String sqdw,String ysl) {
		String acceptNo = "";

		// ====================判断受理号是否存在，更新受理号和汇总字段================
		if (entityId != null && entityId.trim().length() > 0) {
			String isExist = "select ACCEPT_NO from SS_CCGBSQB_V1 where id = "
					+ entityId;
			List list = smartDao.getResultList(isExist);
			if (list != null) {
				Object obj = list.get(0);
				String s = (String) obj;
				if (s == null || s.trim().length() <= 0) {

					// ===================生成受理编号，更新受理编号开始========
					//生成政务中心统一查询编号 开始
					Map<String,String> serialNoAndPasswordMap = null;
		        	serialNoAndPasswordMap = ywMtbjlshInfoService.getSerialNoAndPassword("0");//大厅
		        	String serialNo = serialNoAndPasswordMap.get("serialNo");
		        	String password = serialNoAndPasswordMap.get("password");
		        	//生成政务中心统一查询编号 结束
		        	acceptNo = serialNo;
					String sql = "Update SS_CCGBSQB_V1 SET ACCEPT_NO ='"
							+ serialNo
							+ "',SERIAL_NO='"
							+ serialNo
							+"',PASSWORD='"
							+ password
							+ "' , SJR = '"
							+ this.getLoginUser().getUser().getUserName()
							+ "' where ID = " + entityId;
					smartDao.executeSql(sql);
					// ==================生成受理编号，更新受理编号结束==========

					// 更新汇总
					WfBusInstance entity = wfBusInstanceService
							.getByMasterEntityAndKey("YwGgcs", entityId);
					entity.setBusMemo1(sqdw);
					entity.setBusMemo3(serialNo);
					entity.setBusMemo4("拆除关闭公共厕所许可审批");
					entity.setBusDate2(new Date());
					WfBusInstanceForm form = WfBusInstanceConvertor
							.convertVoToForm(entity);
					wfBusInstanceService.save(form);

				}else if ((s != null && s.trim().length() > 0) && ysl.equals("1")) { // 预受理状态下，更新汇总字段
					//设置收件人  开始
					String sql = "Update SS_CCGBSQB_V1 SET SJR = '"
						+ this.getLoginUser().getUser().getUserName()
						+ "' where ID = " + entityId;
					smartDao.executeSql(sql);
					//设置收件人  结束
					acceptNo = s;
					WfBusInstance entity = wfBusInstanceService
							.getByMasterEntityAndKey("YwGgcs", entityId);
					entity.setBusMemo1(sqdw);
					entity.setBusMemo3(acceptNo);
					entity.setBusMemo4("拆除关闭公共厕所许可审批");
					entity.setBusDate2(new Date());
					WfBusInstanceForm form = WfBusInstanceConvertor
							.convertVoToForm(entity);
					wfBusInstanceService.save(form);

				}  else {
					acceptNo = s;
				}
			}
		}
		return acceptNo;
	}
	
	/**
	 * 到延期页面
	 * @return
	 */
	public String toYqData(){
		LoginUserForm uform=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
		String username=uform.getUser().getUserName();
		this.getRequest().setAttribute("CurrUserName", username);
		
		setOpinions();
		return "yqData";
	}
	
	/**
	 * 插入延期天数补交告知的信息
	 * @return
	 */
	public String insertOtherInfo(){
		Map map=this.getMapByRequest(this.getRequest());
		this.ywGgcsServices.saveOherInfo(map);
		
	  return null;
	}
	
	
	/**
	 * 到补交告知页面
	 * @return
	 */
	public String toBjgzData(){
		LoginUserForm form=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
		String username=form.getUser().getUserName();
		this.getRequest().setAttribute("CurrUserName", username);
		setOpinions();
		return "toBjgzData";
	}
	
	/**
	 * 加载历史意见到呈批表
	 */
	private void setOpinions(){
		String viewName=getRequest().getParameter("viewName");
		if(viewName == null){
			throw new JbpmException("视图参数不能为空，无法正确加载历史意见列表！");
		}
		
		Map<String, List<TraceRecord>> map = null;
		if(viewName.equals(WfActElemPrivDefForm.DB_ZB_VIEW)){
			map = loadWfOpinionsByTaskInstDbid();
			
		}
		else{
			map = loadWfOpinionsByProcInstDbid();
		}		
		if(map != null){
            Iterator it=map.entrySet().iterator();
            while(it.hasNext()){
         	   Map.Entry entrys=(Map.Entry)it.next();
         	   String key=(String) entrys.getKey();
         	  List<TraceRecord>  list=new ArrayList<TraceRecord>();
         	   List<TraceRecord> traceRecords = (List<TraceRecord>) entrys.getValue();
         	   if(traceRecords.size()>0){//只取一条记录
         		  TraceRecord record=null;
         		   for(int k=traceRecords.size()-1;k>=0;k--){
         			   record=traceRecords.get(k);
         			 if(StringUtils.isNotBlank(record.getHandleComments())){
         				list.add(record);
         				map.put(key,  list);
         				break;
            		  }
         		   }
         	   }else{
         		  map.put(key,  traceRecords);
         	   }
          }
		}
		getRequest().setAttribute(WfOpinionTag.WF_OPINIONS, map);
	}
	public void saveDfsj(String entityId,String dfsjStr){
		
		String sql = "Update SS_CCGBSQB_V1 SET DFSJ = '"+dfsjStr+"' where ID = " + entityId;
		smartDao.executeSql(sql);
	}
	
	public void saveSqrq(String entityId,String sqrq){
		String sql = "Update SS_CCGBSQB_V1 SET sqrq = to_date('"+sqrq+"','yyyy-MM-dd')" +
				" , cpsj='" +sqrq+"' where ID = " + entityId;
		smartDao.executeSql(sql);
	}
	/**
	 * 页面保存之前执行业务逻辑 
	 */
	private void executeWfSaveServer() {
		Map<String, Object> map = new HashMap<String, Object>();
		HttpServletRequest request = BaseAction.getRequest();
		this.setEngineMap(map);
		ScriptEngine scriptEngine = ScriptEngineFactory
				.getBindingScriptEngine(map);
		formExecuteService.executeWfSaveServer(scriptEngine, request);
	}

	private void setEngineMap(Map map) {
		map.put("request", BaseAction.getRequest());
		map.put("response", BaseAction.getResponse());
		map.put("service", formExecuteService);
		map.put("page", page);
		map.put("pageMap", pageMap);
		map.put("testService", testService);
	}

	/**
	 * 制文
	 * 
	 * @return
	 * @throws Exception
	 */
	public String makeDocument() throws Exception {
		 //System.out.println(form.getId());
//		 setOpinions();
	
		 form = ywGgcsServices.getSjtzsField(form);
		 String redHeadFilePath="";
		 if (StringUtils.isNotBlank(form.getRedHeadFileId())) {
		      redHeadFilePath = wfBusTemplateServiceEX.getPrintTemplatePath(Long.parseLong(form.getRedHeadFileId()));
		      form.setRedHeadFilePath(redHeadFilePath);
		 }
			//加载收件通知书里面的附件
		 String isred=getRequest().getParameter("isred");
		 //如果要打印红头
		 if("yes".equals(isred)){
			  redHeadFilePath = wfBusTemplateServiceEX.getRedFile(form.getTemplateCode());
		      form.setRedHeadFilePath(redHeadFilePath);
		 }
		 
		 String templateCode = getTemplateCode();
		 if (templateCode != null && templateCode.trim().length() > 0) {
		 String printTemplatePath = wfBusTemplateServiceEX.getPrintTemplatePath(templateCode,WfTemplateAttachmentRefFormEX.ZHENGWEN_TEMPLATE_TYPE);
		 form.setTemplatePath(printTemplatePath);
		 WfTemplateAttachmentRefFormEX wfTemplateAttachmentRefFormEX =(WfTemplateAttachmentRefFormEX) wfTemplateAttachmentRefServiceEX.get(Long.parseLong(form.getZhengwenFileId()));
		 String zhengwenPath = wfTemplateAttachmentRefFormEX.getFilePath()+ "/" + wfTemplateAttachmentRefFormEX.getFileRealName();
		 form.setZhengwenPath(zhengwenPath);
		 System.out.println("getZhengwenPath:" + form.getZhengwenPath());
//		 
//		 //---------行政允许------
		 GgcsForm ggcsForm=ywGgcsServices.get(form.getId());
		 ggcsForm.setZhengwenPath(zhengwenPath);
		 ggcsForm.setCurDate(DateUtilsEX.convertDate2Chinese(new Date()));
		 ggcsForm.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
		 ggcsForm.setCurSeq(String.valueOf(oaDocCodeServiceEX.getCurSeqAndAddSeq(templateCode,wfTemplateAttachmentRefFormEX.getFileCode(),form.getId())));		 
		 //int betweenDays=DateUtilsEX.getDaysBetween(ggcsForm.getZysjqssj(),ggcsForm.getZysjjssj());
		 //if(betweenDays>=0) betweenDays=betweenDays+1;
		 //if(betweenDays<0) betweenDays=betweenDays-1;
		 //ggcsForm.setTian(String.valueOf(betweenDays));
		 ggcsForm.setUsername(this.getLoginUser().getUser().getUserName());
		 ggcsForm.setLxdh(this.getLoginUser().getUser().getMobile());
		 ggcsForm.setSqr(ggcsForm.getSqdw());
		 ggcsForm.setSlDate(DateUtilsEX.convertCommonDate(new Date()));
		 ggcsForm.setGcAddress2(ggcsForm.getGcAddress());
		 ggcsForm.setGcAddress3(ggcsForm.getGcAddress());
//		 dlzyForm.setCsyj(form.getCsyj());
//		 dlzyForm.setFsyj(form.getFsyj());
//		 dlzyForm.setSpyj(form.getSpyj());
//		//---获取受理通知书时间---
		 String sltjFileCode="sltzs";  //受理通知书文件编码
		 YwPrintDocForm ywPrintDocForm=ywPrintDocService.getSltjFile(templateCode,sltjFileCode,form.getId());
         if(ywPrintDocForm!=null)
        	 ggcsForm.setSlDate(DateUtilsEX.convertCommonDate(ywPrintDocForm.getCreatDate()));
//        	 
		    WfUtilsEX.wfBusPrint(ggcsForm);		
		    BaseAction.getRequest().setAttribute("seq", ggcsForm.getCurSeq());
		    BaseAction.getRequest().setAttribute("zhengwenPath",zhengwenPath);
		    BaseAction.getRequest().setAttribute("templateFilePath",zhengwenPath);
			BaseAction.getRequest().setAttribute("fileCode",wfTemplateAttachmentRefFormEX.getFileCode());
			BaseAction.getRequest().setAttribute("entityId", form.getId());
			BaseAction.getRequest().setAttribute("templateId",wfTemplateAttachmentRefFormEX.getId());
		 }
		 
		return WfConstant.MAKE_DOCUMENT;
	}
	
	public String printcz() throws Exception {
		String taskId=getRequest().getParameter("taskInstDbid");
		String activName="";
		if(StringUtils.isNotBlank(taskId)){
		  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
			activName=instance.getActivityName();
		    getRequest().setAttribute("activName", activName);
		}else{
			 getRequest().setAttribute("activName", "");
		}
		if(form.getId() != null && form.getId() > 0){
			//加载收件通知书里面的附件
			 form = ywGgcsServices.getSjtzsField(form);
			 //form.setCurSeq(String.valueOf(oaDocCodeServiceEX.getCurSeqAndAddSeq(form.getTemplateCode(),wfTemplateAttachmentRefFormEX.getFileCode(),form.getId())));		 
			 System.out.println("acceptNo = " + form.getAcceptNo());
    		List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(), form.getFileCode(), form.getId());
        	if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
    			return WfConstant.PRINT_DIR;
    		}
    	}
        return WfUtilsEX.wfBusPrint(form,form.getId(),activName);
    }
	
	public String wfBusYslTuih() throws Exception {
    	try {
    		ywGgcsServices.wfBusYslTuih(form, this.getLoginUser());
			WfBusSaveResult result = new WfBusSaveResult(true, null);
			result.setTask(new WfBusInstanceTaskForm());
			Struts2Utils.renderJson(result);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
        return null;
    }
	
	@Override
	public String delete() throws Exception {
		return null;
	}

	
	@Override
	public String list() throws Exception {

		return null;
	}

	@Override
	protected void prepareModel() throws Exception {
		LoginUserForm uform=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
		String username=uform.getUser().getUserName();
//		if(form==null)
//       	 form=new GgcsForm();
		if(id!=null){
			form =ywGgcsServices.get(id);
		}else{
			form = new GgcsForm();
		}
	
    	//补交告知原因
    	if(form.getBjgzyy()==null){
    		form.setBjgzyy(this.getOpinion("'jbryj','jbrcs'"));
    	}
    	//补交告知时间
    	if(form.getBjgzsj()==null){
    		form.setBjgzsj(new Date());
    	}
    	//受理告知时间
    	if(form.getBjslsj()==null){
    		//form.setBjslsj(new Date());
    	}
    
    	//补交告知发出人
//    	if(form.getBjgzfcr()==null){
//    		form.setBjgzfcr(username);
//    	}
//        //补交告知受理人
//    	if(form.getSldwcbrxm()==null){
//    		form.setSldwcbrxm(username);
//    		
//    	}
    	//补交告知受理地点
    	if(form.getBjsljtdd()==null){
    		form.setBjsljtdd("广州市城市管理委员会");
    	}
    	//答复时间
    	if(id!=null && StringUtils.isNotBlank(this.getTemplateCode())){
    		Date date=this.wfServiceEX.getDfsjByTempleteCode(this.getTemplateCode(),id);
    		form.setDfsj(DateUtilsEX.dateFormate(date,"yyyy-MM-dd"));
    		this.ywGgcsServices.updateDfsj(form);
    	}
	}

	

    
	 private  Map getMapByRequest(HttpServletRequest request) {
	        Map<String, String> map = new HashMap<String, String>();
	        Enumeration enu = request.getParameterNames();
	        while(enu.hasMoreElements()) {   
	            String paraName = (String)enu.nextElement();   
	            String paraValue = request.getParameter(paraName).trim(); 
	            //if(paraValue!=null && !"".equals(paraValue)){
	                map.put(paraName, paraValue);
	            //}           
	        }
	                
	        return map;
	    }
	@Override
	public String save() throws Exception {

		return null;
	}

	public GgcsForm getModel() {
		return form;
	}

	public GgcsForm getForm() {
		return form;
	}

	public void setForm(GgcsForm form) {
		this.form = form;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}	 
}
